package com.micangcaihang.micang.mvp.task.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.View;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.luck.picture.lib.PictureBaseActivity;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.tools.DateUtils;
import com.luck.picture.lib.tools.DoubleUtils;
import com.micangcaihang.common.baserx.RxSchedulers;
import com.micangcaihang.common.http.ApiResult;
import com.micangcaihang.common.http.RxHelper;
import com.micangcaihang.common.http.exception.ApiException;
import com.micangcaihang.common.utils.LoadDialogUtil;
import com.micangcaihang.common.utils.StringUtils;
import com.micangcaihang.common.utils.ToastUtils;
import com.micangcaihang.micang.R;
import com.micangcaihang.micang.entity.TaskAccessoryInfoEntity;
import com.micangcaihang.micang.http.ApiService;
import com.micangcaihang.micang.http.MiSubScriber;

import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;


public class MiPicturePlayAudioActivity extends PictureBaseActivity implements View.OnClickListener {
    public static final int DELETE_FILE_AUDIO = 0x003;
    private String audio_path;
    private MediaPlayer mediaPlayer;
    private SeekBar musicSeekBar;
    private boolean isPlayAudio = false;
    private TextView tv_PlayPause, tv_Stop, tv_Quit, tv_delete,
            tv_musicStatus, tv_musicTotal, tv_musicTime;
    private CompositeDisposable mCompositeDisposable = new CompositeDisposable();
    private TaskAccessoryInfoEntity.FileContentBean fileContentBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
                , WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_play_audio_mi);
        fileContentBean = (TaskAccessoryInfoEntity.FileContentBean) getIntent().getExtras().getSerializable(PictureConfig.EXTRA_PREVIEW_SELECT_LIST);
        if (!StringUtils.isEmpty(fileContentBean.getPath())) {
            audio_path = fileContentBean.getPath();
        } else if (!StringUtils.isEmpty(fileContentBean.getFile_path())) {
            audio_path = fileContentBean.getFile_path();
        }
//        audio_path = getIntent().getStringExtra("audio_path");
        tv_musicStatus = (TextView) findViewById(com.luck.picture.lib.R.id.tv_musicStatus);
        tv_musicTime = (TextView) findViewById(com.luck.picture.lib.R.id.tv_musicTime);
        musicSeekBar = (SeekBar) findViewById(com.luck.picture.lib.R.id.musicSeekBar);
        tv_musicTotal = (TextView) findViewById(com.luck.picture.lib.R.id.tv_musicTotal);
        tv_PlayPause = (TextView) findViewById(com.luck.picture.lib.R.id.tv_PlayPause);
        tv_Stop = (TextView) findViewById(com.luck.picture.lib.R.id.tv_Stop);
        tv_Quit = (TextView) findViewById(com.luck.picture.lib.R.id.tv_Quit);
        tv_delete = (TextView) findViewById(R.id.tv_delete);
        handler.postDelayed(() -> initPlayer(audio_path), 30);
        tv_PlayPause.setOnClickListener(this);
        tv_Stop.setOnClickListener(this);
        tv_Quit.setOnClickListener(this);
        tv_delete.setOnClickListener(this);
        musicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser == true) {
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });
    }

    /**
     * set preview image
     *
     * @param position
     * @param medias
     */
    public static void externalPicturePreview(Fragment fragment, Context context,
                                              int position, TaskAccessoryInfoEntity.FileContentBean medias,
                                              String title) {
        if (!DoubleUtils.isFastDoubleClick()) {
            Intent intent = new Intent(context, MiPicturePlayAudioActivity.class);
            intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, medias);
            intent.putExtra(PictureConfig.EXTRA_POSITION, position);
            intent.putExtra("title", title);
            fragment.startActivityForResult(intent, DELETE_FILE_AUDIO);
            ((Activity) context).overridePendingTransition(R.anim.a5, 0);
        }
    }

    //  通过 Handler 更新 UI 上的组件状态
    public Handler handler = new Handler();
    public Runnable runnable = new Runnable() {
        @Override
        public void run() {
            try {
                if (mediaPlayer != null) {
                    tv_musicTime.setText(DateUtils.timeParse(mediaPlayer.getCurrentPosition()));
                    musicSeekBar.setProgress(mediaPlayer.getCurrentPosition());
                    musicSeekBar.setMax(mediaPlayer.getDuration());
                    tv_musicTotal.setText(DateUtils.timeParse(mediaPlayer.getDuration()));
                    handler.postDelayed(runnable, 200);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 初始化音频播放组件
     *
     * @param path
     */
    private void initPlayer(String path) {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(audio_path);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    mediaPlayer.setLooping(true);
                    tv_PlayPause.setEnabled(true);
                    tv_Stop.setEnabled(true);
                    playAudio();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == com.luck.picture.lib.R.id.tv_PlayPause) {
            playAudio();

        }
        if (i == com.luck.picture.lib.R.id.tv_Stop) {
            tv_musicStatus.setText(getString(com.luck.picture.lib.R.string.picture_stop_audio));
            tv_PlayPause.setText(getString(com.luck.picture.lib.R.string.picture_play_audio));
            stop(audio_path);

        }
        if (i == com.luck.picture.lib.R.id.tv_Quit) {
            handler.removeCallbacks(runnable);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    stop(audio_path);
                }
            }, 30);
            try {
                closeActivity();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (i == R.id.tv_delete) {
            new MaterialDialog.Builder(MiPicturePlayAudioActivity.this)
                    .content("确定删除当前录音吗?")
                    .positiveText("确定")
                    .negativeText("取消")
                    .onPositive((dialog, which) -> deleteAudio())
                    .show();
        }
    }

    private void deleteAudio() {
        Observable<ApiResult<Void>> observable = ApiService.util_delete(fileContentBean.getFile_id());
        mCompositeDisposable.add(observable.compose(RxSchedulers.observableIoToMain())
                .compose(RxHelper.handleResult())
                .subscribeWith(new MiSubScriber<ApiResult<Void>>() {
                    @Override
                    protected void doOnError(ApiException e) {
                        super.doOnError(e);
                    }

                    @Override
                    protected void doOnStart() {
                        LoadDialogUtil.showMaterLoading(MiPicturePlayAudioActivity.this, "");
                    }

                    @Override
                    protected void doOnNext(ApiResult<Void> voidApiResult) {
                        setResult(RESULT_OK);
                        ToastUtils.showLong("删除成功");
                        finish();
                        overridePendingTransition(0, com.luck.picture.lib.R.anim.a3);
                    }

                    @Override
                    protected void doOnComplete() {
                        LoadDialogUtil.hideMaterLoading();
                    }
                }));
    }


    /**
     * 播放音频
     */
    private void playAudio() {
        if (mediaPlayer != null) {
            musicSeekBar.setProgress(mediaPlayer.getCurrentPosition());
            musicSeekBar.setMax(mediaPlayer.getDuration());
        } else {
            return;
        }
        String ppStr = tv_PlayPause.getText().toString();
        if (ppStr.equals(getString(com.luck.picture.lib.R.string.picture_play_audio))) {
            tv_PlayPause.setText(getString(com.luck.picture.lib.R.string.picture_pause_audio));
            tv_musicStatus.setText(getString(com.luck.picture.lib.R.string.picture_play_audio));
            playOrPause();
        } else {
            tv_PlayPause.setText(getString(com.luck.picture.lib.R.string.picture_play_audio));
            tv_musicStatus.setText(getString(com.luck.picture.lib.R.string.picture_pause_audio));
            playOrPause();
        }
        if (isPlayAudio == false) {
            handler.post(runnable);
            isPlayAudio = true;
        }
    }

    /**
     * 停止播放
     *
     * @param path
     */
    public void stop(String path) {
        if (mediaPlayer != null) {
            try {
                mediaPlayer.stop();
                mediaPlayer.reset();
                mediaPlayer.release();
                handler.removeCallbacks(runnable);
                tv_PlayPause.setEnabled(false);
                tv_Stop.setEnabled(false);
                mediaPlayer = null;
                mediaPlayer = new MediaPlayer();
                try {
                    mediaPlayer.setDataSource(audio_path);
                    mediaPlayer.prepareAsync();
                    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mediaPlayer.setLooping(true);
                            tv_PlayPause.setEnabled(true);
                            tv_Stop.setEnabled(true);
                            isPlayAudio = false;
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 暂停播放
     */
    public void playOrPause() {
        try {
            if (mediaPlayer != null) {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                } else {
                    mediaPlayer.start();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        closeActivity();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null && handler != null) {
            handler.removeCallbacks(runnable);
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
}
